<?php
namespace app\index\controller;
use think\Controller;
use app\model\User as UserModel;
use app\model\Ram as RamModel;
use app\model\UserToken as UserTokenModel;
use think\Db;

class Base extends Controller
{
    public $login_user = [];

    public function __construct(){
        parent::__construct();
        // 验证token
        $action = $this->request->action();
        // $controller = explode('.', $this->request->controller())[2];
        // 验证token
        if (!empty($this->noCheckToken)) {
            $noCheckToken = array_map('strtolower',$this->noCheckToken);
        }else{
            $noCheckToken = [];
        }
        if ( !in_array($action, $noCheckToken) || !empty($this->request->header()['x-access-token']) ) {
            if ( empty($this->request->header()['x-access-token']) ) {
                // exception('token不能为空',9000);
            }
            $access_token = $this->request->header()['x-access-token'];
            // $access_token = 'E2ED5201F4AA45569E3286F1B291B8D9';
            $token = UserTokenModel::where('access_token',$access_token)->find();
            if ( empty($token) ) {
                exception('token无效',401);
            }
            if ( time() > strtotime($token['expiry_time']) ) {
                exception('token已过期',401);
            }

            if ($token['utype'] == 1) {
                $data = RamModel::where('id',$token['ram_id'])->find();
            }else{
                $data = UserModel::where('id',$token['user_id'])->find();
            }
            if ($data['status'] != 1) {
                exception('账号已禁用',9000);
            }
            

            $this->login_user = [
                'user_id'=>$token['user_id'],
                'utype'=>$token['utype'],
                'ram_id'=>$token['ram_id'],
            ];
        }
    }

    /**
     * [uploadFile description]
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:30+0800
     * @return   [description]
     */
    public function uploadFileOss(){
        $file = $_FILES['file'];
        if (empty($file)) {
            return apiResult('5000','未检测到图片');
        }
        $ext = explode(".", $file['name']);//拆分获取图片名
        $ext = $ext[count($ext) - 1];//取图片的后缀名
        $ext = strtolower($ext);
        Db::name('test')->insert(['content'=>$ext]);
        $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt','heic'];
        if (!in_array($ext, $types)) {
            return apiResult('5000','文件格式不支持，请上传标准图片文件');
        }
        $result = uploadFile($file['name'],$file['tmp_name'],date('Ymd').'/');

        if ($result['status'] == 1) {
            return apiResult('2000','上传成功',[
                'extension'=>$ext,
                'savename'=>$result['data'],
                'filename'=>$file['name']
            ]);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    /**
     * 上传图片
     * @Author   CCH
     * @DateTime 2020-08-15T17:26:24+0800
     * @return   [type]                   [description]
     */
    public function uploadFile(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $filename = $file->getInfo()['name'];
            $ext = explode(".", $filename);//拆分获取图片名
            $ext = $ext[count($ext) - 1];//取图片的后缀名
            $ext = strtolower($ext);
            Db::name('test')->insert(['content'=>$ext]);
            $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt','heic'];
            if (!in_array($ext, $types)) {
                return json(['code'=>5000,'msg'=>'文件格式不支持，请上传标准图片文件']);
            }
            $info = $file->move('./uploads');
            if($info){
                return apiResult('2000','上传成功',[
                    'extension'=>$ext,
                    'savename'=>str_replace('\\', '/', $info->getSaveName()),
                    'filename'=>$filename
                ]);
            }else{
                return apiResult('5000',$file->getError());
            }
        }
    }



    /**
     * 生成二维码
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:21+0800
     * @param    $path  路径
     * @param    $width 宽度
     * @return   返回图片base数据给前端小程序，直接放前端img src即可显示
     */
    public function createQrCode($path,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {

            return apiResult('2000','二维码生成成功',"data:image/jpeg;base64,".base64_encode( $result ));
        }else{
            return apiResult('5000','二维码生成失败');
        }
    }

    /**
     * 生成二维码
     * @Author   CCH
     * @DateTime 2020-06-07T17:25:21+0800
     * @param    $path  路径
     * @param    $width 宽度
     * @return   返回图片base数据给前端小程序，直接放前端img src即可显示
     */
    public function createQrCodeOss($path,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {
            $image = uploadFileString($result,'appraisal/app/');
            if ($image['status'] == 1) {
                return apiResult('2000','二维码生成成功',$image['data']);
            }else{
                return apiResult('5000','上传失败');
            }
        }else{
            return apiResult('5000','二维码生成失败');
        }
    }

    public function createUnlimitedCodeOss($path,$scene,$width=150){
        $config = config('config.wxparam');
        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['appid'].'&secret='.$config['secret'];
        $access_token = httpRequest( $access_token_url );
        $access_token = json_decode($access_token,true); 
        if (empty($access_token['access_token'])) {
            return apiResult('5000','access_token获取失败');
        }

        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token['access_token'];
        $param = json_encode(array("path"=>$path,'scene'=>$scene,"width"=> 150));
        $result = httpRequest( $qcode, $param , "POST");
        if (!empty($result)) {
            return apiResult('2000','二维码生成成功',"data:image/jpeg;base64,".base64_encode( $result ));
        }else{
            return apiResult('5000','二维码生成失败');
        }
        // if (!empty($result)) {
        //     $image = uploadFileString($result,'bwc/app/');
        //     if ($image['status'] == 1) {
        //         return apiResult('2000','二维码生成成功',$image['data']);
        //     }else{
        //         return apiResult('5000','上传失败');
        //     }
        // }else{
        //     return apiResult('5000','二维码生成失败');
        // }
    }

}
